import { Injectable, NotFoundException } from '@nestjs/common';
import { CreatePictureDto } from './dto/create-picture.dto';
import { UpdatePictureDto } from './dto/update-picture.dto';
import { Picture } from './entities/picture.entity';
import { Repository, In } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
@Injectable()
export class PictureService {

  constructor(
    @InjectRepository(Picture)
    private readonly pictureRepository: Repository<Picture>,
  ) {}

  async create(createPictureDto: CreatePictureDto) {
    const picture = this.pictureRepository.create(createPictureDto);
    const insertRes = await this.pictureRepository.insert(picture);
    return insertRes.raw;
  }

  async createForScript(createPictureDto: CreatePictureDto) {
    const picture = this.pictureRepository.create(createPictureDto);
    const insertRes = await this.pictureRepository.insert(picture);
    return insertRes.raw[0].id;
  }

  async findAll(): Promise<Picture[]> {
    return this.pictureRepository.find();
  }

  async findOne(id: string): Promise<Picture> {
    return this.pictureRepository.findOne({ where: { id: id } });
  }

  async findByIds(ids: string[]): Promise<Picture[]> {
    return this.pictureRepository.find({
      where: {
        id: In(ids), // 使用TypeORM的In操作符
      },
    });
  }

  async findPictureListByUser(creator: string): Promise<Picture[]> {
    return this.pictureRepository.find({ where: { creator: creator } });
  }

  async update(id: string, updatePictureDto: UpdatePictureDto) {
    const result = await this.pictureRepository.update(id, updatePictureDto);

    if (result.affected === 0) {
      throw new NotFoundException(`Picture with ID "${id}" not found.`);
    }
  }

  async remove(id: string) {
    try {
      const result = await this.pictureRepository.delete({ id: id });

      if (result.affected && result.affected > 0) {
        return `成功删除 ${result.affected} 条记录`;
      } else {
        return `未找到匹配的记录，没有进行删除操作`;
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }
}
